<template>
  <Header :url="userImageUrl" />
  <div class="learning-container">
    <div class="sidebar">
      <button @click="toHome" class="home-btn">
        <span class="icon">🏠</span>
        <span>返回主页</span>
      </button>
      <div class="progress-info" v-if="!isFinished">
        <div class="progress-circle">
          <svg width="60" height="60" viewBox="0 0 120 120">
            <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
            <circle cx="60" cy="60" r="54" fill="none" stroke="#5e72e4" stroke-width="12" 
              :stroke-dasharray="339.292"
              :stroke-dashoffset="339.292 * (1 - (currentProgress / totalWords))"
              transform="rotate(-90 60 60)"
            />
          </svg>
          <span class="progress-text">{{ currentProgress }}/{{ totalWords }}</span>
        </div>
        <p class="progress-label">学习进度</p>
      </div>
    </div>
    
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>正在准备单词...</p>
      </div>
      
      <!-- 学习状态 -->
      <div v-else-if="showWordPanel && !isFinished" class="learning-panel">
        <audio ref="phonePlayer" :src="phoneUrl"></audio>
        
        <div class="word-display">
          <h1 class="word-text">{{ wordText }}</h1>
          <div class="pronunciation">
            <button class="pronunciation-switch" @click="switchPhone">
              {{ phoneType === 0 ? '美' : '英' }}
            </button>
            <span class="phone-text" @click="playPhone">{{ phone }}</span>
          </div>
        </div>
        
        <!-- 选项按钮区域 -->
        <div v-if="showBtnPanel" class="options-container">
          <button 
            v-for="(btn, idx) in btnText" :key="idx"
            :disabled="btndisabled"
            :ref="el => { if(el) answerBtns[idx] = el }"
            @click="check($event, idx)"
            :class="{ 
              'option-btn': true, 
              'shake': shakeActivated[idx], 
              'correct': isCorrect[idx]
            }"
          >
            {{ btn }}
          </button>
        </div>
        
        <!-- 单词详情面板 -->
        <div v-if="showInfoPanel" class="word-details">
          <div class="translations">
            <h3>词义</h3>
            <div v-for="(tran, index) in trans" :key="index" class="translation-item">
              <span class="word-type">{{ tran.wordType }}</span>
              <span class="meaning">{{ tran.cnTran }}</span>
            </div>
          </div>
          
          <div v-if="showPhrases" class="phrases">
            <h3>常用短语</h3>
            <div v-for="(phrase, index) in phrases" :key="index" class="phrase-item">
              <p class="en">{{ phrase.enPhrase }}</p>
              <p class="cn">{{ phrase.cnPhrase }}</p>
            </div>
          </div>
          
          <div v-if="showSentences" class="sentences">
            <h3>例句</h3>
            <div v-for="(sentence, index) in sentences" :key="index" class="sentence-item">
              <p class="en">{{ sentence.enSentence }}</p>
              <p class="cn">{{ sentence.cnSentence }}</p>
            </div>
          </div>
          
          <div v-if="showRem" class="memory-tips">
            <h3>记忆方法</h3>
            <p>{{ remMethod }}</p>
          </div>
          
          <button @click="showMemoryPage" class="continue-btn">
            继续学习 <span class="icon">→</span>
          </button>
        </div>
      </div>
      
      <!-- 完成状态 -->
      <div v-if="showFinishedPanel" class="finished-panel">
        <div class="celebration">
          <span class="confetti">🎉</span>
          <h2>恭喜你！本轮学习已完成</h2>
          <p>今天又进步了一点点，继续保持！</p>
        </div>
        
        <div class="action-buttons">
          <button @click="toHome" class="action-btn home">
            <span class="icon">☕</span> 休息一下
          </button>
          <button @click="nextBatch" class="action-btn next">
            <span class="icon">📚</span> 继续学习
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import WordList from "@/utils/list.js";
import request from "@/utils/request.js";
import Header from "@/components/Header.vue";

export default {
  name: "Learning1",
  components: { Header },
  data() {
    return {
      loading: true,
      isFinished: false,
      allwords: {},
      words: {},
      totalWords: 0,
      currentProgress: 0,
      userNeedCount: 0,
      batch: 1,
      phoneType: 0,
      btnText: ["选项1", "选项2", "选项3", "选项4"],
      answerBtns: [],
      shakeActivated: [false, false, false, false],
      isCorrect: [false, false, false, false],
      showWordPanel: true,
      showBtnPanel: true,
      showInfoPanel: false,
      showFinishedPanel: false,
      btndisabled: false,
      showPhrases: true,
      showSentences: true,
      showRem: true,
      userImageUrl: this.$store.getters.userImageUrl,
      startTime: new Date(),
    };
  },
  computed: {
    wordText() {
      if (!this.words || !this.words.current || !this.words.current.data) 
        return "";
      return this.words.current.data.word;
    },
    phonelog() { 
      return this.phoneType === 0 ? "美" : "英"; 
    },
    phone() { 
      return this.phoneType === 1 ? this.words.data().ukPhone : this.words.data().usPhone; 
    },
    phoneUrl() { 
      return "http://dict.youdao.com/dictvoice?type=" + this.phoneType + "&audio=" + this.wordText; 
    },
    trans() { 
      return this.words.data().translations; 
    },
    sentences() {
      this.showSentences = this.words.data().sentences?.length > 0;
      return this.words.data().sentences;
    },
    phrases() {
      this.showPhrases = this.words.data().phrases?.length > 0;
      return this.words.data().phrases;
    },
    remMethod() {
      this.showRem = this.words.data().remMethod !== null && this.words.data().remMethod !== "";
      return this.words.data().remMethod;
    },
  },
  methods: {
    // 切换发音类型
    switchPhone() {
      this.phoneType = this.phoneType === 0 ? 1 : 0;
      setTimeout(() => { this.playPhone(); }, 200);
    },
    
    // 播放读音
    playPhone() { 
      this.$refs.phonePlayer.play(); 
    },
    
    // 检查选择是否正确
    check(event, index) {
      const text = this.btnText[index];
      this.btndisabled = true;
      
      // 无论正确与否，只要选择了选项就更新学习进度
      this.currentProgress++;
      
      if (text === this.getTrans(this.trans)) {
        // 答对了
        this.updateLearningRequest(this.words.data().wordID);
        this.isCorrect[index] = true;
        this.words.current.strangeDegree -= 1;
        
        setTimeout(() => { 
          this.isCorrect[index] = false; 
        }, 1000);
      } else {
        // 答错了
        this.shakeActivated[index] = true;
        
        setTimeout(() => { 
          this.shakeActivated[index] = false; 
        }, 1000);
      }
      
      // 显示详情
      setTimeout(() => { 
        this.showInfo(); 
      }, 1000);
    },
      
    // 获取新单词
    getNewWords() {
      this.loading = true;
      let userJson = localStorage.getItem("user");
      let user = JSON.parse(userJson);
      this.userNeedCount = user.needCount;
      
      // 每次请求获取用户设置的needCount数量的单词
      request.get("/memory/newWords", {
        params: { 
          userID: user.userID, 
          needCount: this.userNeedCount
        },
      }).then((res) => {
        if (res.data && res.data.length > 0) {
          this.words = new WordList(res.data);
          this.allwords = new WordList(res.data.slice());
          
          // 总单词数始终为用户设置的单词数量
          this.totalWords = this.userNeedCount;
          
          // 只在第一批次时重置进度，其余时候保持原来的进度
          if (this.batch === 1) {
            this.currentProgress = 0;
          }
          
          this.showBtns();
          this.isFinished = false;
        } else {
          console.warn("返回的单词数据为空");
          this.words = new WordList([]);
          this.allwords = new WordList([]);
          
          if (this.batch === 1) {
            this.totalWords = 0;
            this.currentProgress = 0;
          }
          this.showFinished();
        }
        this.loading = false;
      }).catch(err => {
        console.error("获取单词失败", err);
        this.loading = false;
      });
    },
    
    // 更新选项    
    updateExplans() {
      if (this.isFinished) return;
      
      try {
        // 检查words对象是否正确初始化
        if (!this.words || !this.words.current || !this.words.current.data || typeof this.words.data !== 'function') {
          console.warn("words对象未正确初始化");
          this.generateFallbackOptions();
          return;
        }
        
        // 检查allwords是否正确初始化
        if (!this.allwords || !this.allwords.length || this.allwords.length <= 1 || typeof this.allwords.getFourNodes !== 'function') {
          console.warn("allwords对象未正确初始化或单词数量不足");
          this.generateFallbackOptions();
          return;
        }
        
        var randomWords = this.allwords.getFourNodes();
        if (!randomWords || !Array.isArray(randomWords) || randomWords.length < 1) {
          console.warn("getFourNodes返回的数据异常");
          this.generateFallbackOptions();
          return;
        }
        
        var flag = false;
        
        for (var word of randomWords) {
          if (word && word.data && this.words.current && this.words.current.data && 
              word.data.wordID == this.words.current.data.wordID) {
            flag = true;
          }
        }
        
        if (!flag) {
          try {
            var index = this.words.randomNum(0, 3);
            randomWords.splice(index, 1, this.words.current);
          } catch (e) {
            console.warn("插入当前单词选项失败:", e);
          }
        }
        
        var explans = [];
        for (var word of randomWords) {
          // 确保节点有效且有翻译数据
          if (word && word.data && word.data.translations) {
            explans.push(this.getTrans(word.data.translations));
          } else {
            explans.push("未知选项");
          }
        }
        
        // 确保生成了足够的选项
        if (explans.length < 4) {
          for (let i = explans.length; i < 4; i++) {
            explans.push(`选项${i+1}`);
          }
        }
        
        this.btnText = explans;
      } catch (error) {
        console.error("更新选项时出错:", error);
        this.generateFallbackOptions();
      }
    },
    
    // 生成备选选项
    generateFallbackOptions() {
      try {
        // 首先检查words对象是否正确初始化
        if (!this.words || !this.words.current || !this.words.current.data) {
          // words对象未正确初始化，使用默认选项
          this.btnText = [
            "n.选项1;v.示例选项;",
            "adj.选项2;n.测试内容;",
            "adv.选项3;prep.预设内容;",
            "n.选项4;v.示例内容;"
          ];
          return;
        }
        
        // 直接使用this.words.current.data来获取当前单词的翻译
        let currentTranslations = this.words.current.data.translations || [];
        const currentTrans = this.getTrans(currentTranslations);
        let options = [currentTrans];
        
        // 生成随机错误选项
        const fakeTrans = [
          "n.错误选项1;v.测试选项;",
          "adj.错误选项2;n.测试内容;",
          "adv.错误选项3;prep.预设内容;"
        ];
        
        // 随机打乱选项顺序
        options = options.concat(fakeTrans);
        for (let i = options.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [options[i], options[j]] = [options[j], options[i]];
        }
        
        this.btnText = options;
      } catch (error) {
        console.error("生成备选选项时出错:", error);
        // 发生错误时使用默认选项
        this.btnText = [
          "n.默认选项1;v.示例选项;",
          "adj.默认选项2;n.测试内容;",
          "adv.默认选项3;prep.预设内容;",
          "n.默认选项4;v.示例内容;"
        ];
      }
    },
    
    // 获取翻译文本
    getTrans(trans) {
      var res = "";
      for (var tran of trans) {
        res += tran.wordType + "." + tran.cnTran + ";";
      }
      return res;
    },
    
    // 显示单词详情
    showInfo() {
      this.showBtnPanel = false;
      this.showInfoPanel = true;
      this.showWordPanel = true;
      this.playPhone();
    },
    
    // 显示下一个单词
    showMemoryPage() {
      // 检查是否学完了当前批次的所有单词
      if (this.currentProgress % this.totalWords==0) {
        this.showFinished();
        return;
      }
      
      if (this.words.length <= 1) {
        this.showFinished();
        return;
      }
      
      this.words.next();
      this.showWordPanel = true;
      this.showBtnPanel = true;
      this.showInfoPanel = false;
      this.btndisabled = false;
      this.updateExplans();
    },
    
    // 更新学习记录
    updateLearningRequest(wordID) {
      let userJson = localStorage.getItem("user");
      let user = JSON.parse(userJson);
      request.post("/memory/newWord", { 
        userID: user.userID, 
        wordID: wordID 
      });
    },
    
    // 返回主页
    toHome() { 
      this.$router.push("/"); 
    },
    
    // 获取下一批单词
    nextBatch() { 
      this.batch++; // 增加批次计数
      // 不重置当前进度，保持原有进度
      this.getNewWords(); 
    },
    
    // 显示按钮
    showBtns() {
      this.showWordPanel = true;
      this.showBtnPanel = true;
      this.showInfoPanel = false;
      this.showFinishedPanel = false;
      this.btndisabled = false;
      this.updateExplans();
    },
    
    // 显示完成页面
    showFinished() {
      this.isFinished = true;
      this.showWordPanel = false;
      this.showBtnPanel = false;
      this.showInfoPanel = false;
      this.showFinishedPanel = true;
    },
  },
  created() {
    this.getNewWords();
    
    // 键盘事件监听
    document.onkeydown = (e) => {
      let key = e.keyCode || e.which;
      if (key == 13) { // Enter 键
        if (this.showInfoPanel) {
          this.showMemoryPage();
        }
      } else if (key >= 49 && key <= 52 && this.showBtnPanel && !this.btndisabled) {
        // 1-4 数字键用于选择答案
        const index = key - 49;
        this.check(null, index);
      } else if (key == 32) { // 空格键
        this.playPhone();
        e.preventDefault();
      }
    };
    
    this.startTime = new Date();
  },
  mounted() {
    if (!this.isFinished) {
      this.updateExplans();
    }
  },
  beforeUnmount() {
    // 移除键盘事件监听
    document.onkeydown = null;
    
    // 记录学习时间
    let userJson = localStorage.getItem("user");
    let user = JSON.parse(userJson);
    var endTime = new Date();
    var learningSpan = (endTime.getTime() - this.startTime.getTime()) / 1000 / 60;
    
    request.put("/memory/learningTime", {
      userID: user.userID,
      learningTime: parseInt(learningSpan),
    });
  }
};
</script>

<style scoped>
/* 整体布局 */
.learning-container {
  display: flex;
  min-height: calc(100vh - 70px);
  background-color: #f8f9fe;
}

/* 侧边栏 */
.sidebar {
  width: 200px;
  background: linear-gradient(135deg, #5e72e4 0%, #825ee4 100%);
  padding: 30px 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
}

.home-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 12px;
  color: white;
  padding: 10px 15px;
  width: 100%;
  font-size: 16px;
  margin-bottom: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.home-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.progress-info {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-circle {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.progress-text {
  position: absolute;
  font-size: 14px;
  font-weight: 600;
}

.progress-label {
  margin-top: 10px;
  font-size: 14px;
  opacity: 0.9;
}

/* 主要内容区 */
.main-content {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(94, 114, 228, 0.2);
  border-radius: 50%;
  border-top-color: #5e72e4;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 学习面板 */
.learning-panel {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 单词展示 */
.word-display {
  text-align: center;
  margin-bottom: 40px;
}

.word-text {
  font-size: 64px;
  margin-bottom: 10px;
  color: #32325d;
  letter-spacing: 2px;
  animation: fadeIn 0.5s ease;
}

.pronunciation {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.pronunciation-switch {
  background: #5e72e4;
  color: white;
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.pronunciation-switch:hover {
  background: #4a5cd0;
}

.phone-text {
  font-size: 20px;
  color: #525f7f;
  cursor: pointer;
}

.phone-text:hover {
  color: #5e72e4;
  text-decoration: underline;
}

/* 选项按钮 */
.options-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  width: 100%;
}

.option-btn {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 15px;
  padding: 20px;
  font-size: 17px;
  color: #525f7f;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: left;
  line-height: 1.5;
  min-height: 100px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.option-btn:hover:not(:disabled) {
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  border-color: #5e72e4;
}

.option-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.option-btn.correct {
  background: rgba(66, 186, 150, 0.2);
  border-color: #42ba96;
  animation: pulse 1s;
}

.option-btn.shake {
  animation: shake-horizontal 0.8s cubic-bezier(0.455, 0.03, 0.515, 0.955) both;
  background-color: rgba(249, 37, 36, 0.1);
  border-color: #fa5252;
}

@keyframes shake-horizontal {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70% { transform: translateX(-10px); }
  20%, 40%, 60% { transform: translateX(10px); }
  80% { transform: translateX(8px); }
  90% { transform: translateX(-8px); }
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(66, 186, 150, 0.5); }
  70% { box-shadow: 0 0 0 15px rgba(66, 186, 150, 0); }
  100% { box-shadow: 0 0 0 0 rgba(66, 186, 150, 0); }
}

/* 单词详情 */
.word-details {
  width: 100%;
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 15px 35px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
  animation: slideUp 0.5s ease;
}

.word-details h3 {
  color: #5e72e4;
  font-size: 18px;
  margin-bottom: 15px;
  font-weight: 600;
}

.translations {
  margin-bottom: 25px;
}

.translation-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.word-type {
  background: #f8f9fe;
  padding: 4px 10px;
  border-radius: 15px;
  font-size: 14px;
  color: #5e72e4;
  margin-right: 10px;
  font-weight: 500;
}

.meaning {
  font-size: 16px;
  color: #525f7f;
}

.phrases, .sentences {
  margin-bottom: 25px;
  border-top: 1px solid #e2e8f0;
  padding-top: 20px;
}

.phrase-item, .sentence-item {
  margin-bottom: 15px;
}

.memory-tips {
  background: #f8f9fe;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 25px;
  border-left: 4px solid #5e72e4;
}

.en {
  font-size: 16px;
  color: #32325d;
  margin-bottom: 5px;
}

.cn {
  font-size: 14px;
  color: #8898aa;
}

.continue-btn {
  background: #5e72e4;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 12px 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
}

.continue-btn:hover {
  background: #4a5cd0;
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

/* 完成面板 */
.finished-panel {
  width: 100%;
  max-width: 600px;
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
  text-align: center;
  animation: bounceIn 0.75s;
}

.celebration {
  margin-bottom: 40px;
}

.confetti {
  font-size: 60px;
  display: block;
  margin-bottom: 20px;
  animation: bounce 2s infinite;
}

.celebration h2 {
  font-size: 28px;
  color: #32325d;
  margin-bottom: 10px;
}

.celebration p {
  color: #8898aa;
  font-size: 18px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-btn {
  padding: 12px 25px;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn.home {
  background: #f7fafc;
  color: #8898aa;
}

.action-btn.next {
  background: #5e72e4;
  color: white;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

/* 动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes bounceIn {
  0% { transform: scale(0.8); opacity: 0; }
  50% { transform: scale(1.05); opacity: 1; }
  100% { transform: scale(1); }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-20px); }
  60% { transform: translateY(-10px); }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .learning-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    padding: 15px 30px;
  }
  
  .home-btn {
    width: auto;
    margin-bottom: 0;
  }
  
  .progress-info {
    margin-top: 0;
    flex-direction: row;
    align-items: center;
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .options-container {
    grid-template-columns: 1fr;
  }
}
</style>